<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 *
 * 创建时间：2021-10-31 18:00:03
 *
 * 项目：/levfm  -  $  - AdminFormsController.php
 *
 * 作者：{{AUTO GENERATE}}
 */

//此文件使用程序自动生成，下次生成时【不会】覆盖。
//在这里可以补充、完善你的程序逻辑

namespace modules\levfm\controllers;

use Lev;
use lev\base\Viewv;
use lev\helpers\cacheFileHelpers;
use lev\helpers\UrlHelper;
use modules\levfm\controllers\_gen\BaseAdminForms;
use modules\levfm\helpers\fmUrlHelper;
use modules\levfm\helpers\UrlfmHelper;
use modules\levfm\levfmHelper;
use modules\levfm\table\form\Form_levfm_forms\Form_levfm_forms;
use modules\levfm\table\LevfmFields;
use modules\levfm\table\LevfmForms;

!defined('INLEV') && exit('Access Denied LEV');

class BaseAdminFormsMiddle extends BaseAdminForms
{

    public static function actionTotalnum() {
        $formid = floatval(Lev::GPv('opid'));
        LevfmForms::updateTotalnum($formid, null);
        Lev::showMessages(Lev::responseMsg());
    }

    /**
     * 导出表单
     */
    public static function actionExport() {
        $formid = floatval(Lev::GPv('formid'));
        $formInfo = LevfmForms::findOne(['id'=>$formid]);
        if (empty($formInfo)) {
            Lev::showMessages(Lev::responseMsg(-444, '抱歉，表单不存在：'.$formid));
        }

        unset($formInfo['totalitem'], $formInfo['totalnum']);

        $inLev = levfmHelper::getCheckINLEVphpcode();
        $file = dirname(__DIR__).'/migrations/export/formid_'.$formid;
        cacheFileHelpers::mkdirv($file);

        $data = '<?php '.$inLev.' return ' . cacheFileHelpers::varExportSerialize($formInfo);
        file_put_contents($file . '/formInfo.php', $data);

        $formFields = LevfmFields::getFormFields($formid);
        if ($formFields) {
            $data = '<?php ' . $inLev . ' return ' . cacheFileHelpers::varExportSerialize($formFields);
            file_put_contents($file . '/formFields.php', $data);
        }
        Lev::showMessages(Lev::responseMsg());
    }

    /**
     * 导入表单模板列表
     */
    public static function actionImportList() {
        $lists = glob(dirname(__DIR__) . '/migrations/export/formid_*');
        Viewv::render(static::$tmpPath . '/import-list/import_list.php', [
            'lists' => $lists,
        ]);
    }

    /**
     * 导入表单
     */
    public static function actionImport() {
        $formid = floatval(Lev::GPv('formid'));
        $imformid = floatval(Lev::GPv('imformid'));
        if (!is_file($file = dirname(__DIR__) . '/migrations/export/formid_'.$imformid.'/formInfo.php')) {
            Lev::showMessages(Lev::responseMsg(-444, '抱歉，导入表单信息不存在：'.$imformid));
        }

        $imForm = include $file;
        $imForm['imformid'] = $formid;
        $imForm['uptime']   = Lev::$app['timestamp'];
        $imForm['addtime']  = Lev::$app['timestamp'];
        $imForm = LevfmForms::safeColumns($imForm);

        $create = Lev::GPv('create');
        if ($create) {
            if (!Lev::GPv('doit')) {
                $confirmurl = Lev::toCurrent(['doit' => 1]);
                $tips = '您确定要全新创建吗？<br><tips>全新创建表单【' . $imForm['name'] . '】</tips>';
                Lev::showMessages(
                    Lev::responseMsg(-555, $tips, ['confirmurl' => $confirmurl]),
                    -1, $confirmurl, 'submit'
                );
            }
            unset($imForm['id']);
            $ck = LevfmForms::insert($imForm, true);
            $formid = $ck;
        }else {
            $formInfo = LevfmForms::findOne(['id' => $formid]);
            if (!empty($formInfo)) {
                if (!Lev::GPv('doit')) {
                    $confirmurl = Lev::toCurrent(['doit' => 1]);
                    $tips = '您确定要完全覆盖吗？<br><tips>表单【' . $formInfo['name'] . '】已经存在</tips>';
                    Lev::showMessages(
                        Lev::responseMsg(-555, $tips, ['confirmurl' => $confirmurl]),
                        -1, $confirmurl, 'submit'
                    );
                }


                unset($imForm['id'], $imForm['addtime']);
                $ck = LevfmForms::update($imForm, ['id' => $formid]);
            } else {
                $ck = LevfmForms::insert($imForm, true);
                $formid = $ck;
            }
        }

        if ($ck && is_file($file = dirname(__DIR__) . '/migrations/export/formid_'.$imformid.'/formFields.php')) {
            $imFields = include $file;
            $ckFields = $create ? [] : LevfmFields::getFormFields($formid);
            foreach ($imFields as $imField) {
                $imField = LevfmFields::safeColumns($imField);
                $imField['formid'] = $formid;
                $imField['uptime'] = Lev::$app['timestamp'];
                $imField['addtime']= Lev::$app['timestamp'];
                if ($create) {
                    unset($imField['id']);
                    LevfmFields::insert($imField, true);
                }else {
                    if (isset($ckFields[$imField['inputname']])) {
                        unset($imField['id'], $imField['addtime']);
                        LevfmFields::update($imField, ['id' => $ckFields[$imField['inputname']]['id']]);
                    } else {
                        if (LevfmFields::findOne(['id' => $imField['id']])) unset($imField['id']);
                        LevfmFields::insert($imField, true);
                    }
                }
            }
        }

        Lev::showMessages(Lev::responseMsg($ck ? 1 : -1));
    }

    public static function headerHtm()
    {
        //return parent::headerHtm(); // TODO: Change the autogenerated stub
        //return '<tips class="gray inblk scale8">自定义headerHtm：文件位置：'.__DIR__ . '/AdminFormsController.php'.'</tips>';
    }

    public static function footerHtm()
    {
        //return parent::footerHtm(); // TODO: Change the autogenerated stub
        //return '<tips class="gray inblk scale8">自定义footerHtm</tips>';
    }

    public static function cardFooterButtons($btns = [])
    {
        return parent::cardFooterButtons($btns); // TODO: Change the autogenerated stub
        //return '<tips class="gray inblk scale8">自定义cardFooterButtons</tips>';
    }

    public static function headerViewHtm()
    {
        return parent::headerViewHtm(); // TODO: Change the autogenerated stub
        //return '<tips class="gray inblk scale8">自定义headerViewHtm：文件位置：'.__DIR__ . '/AdminFormsController.php'.'</tips>';
    }

    public static function footerViewHtm()
    {
        return parent::footerViewHtm(); // TODO: Change the autogenerated stub
        //return '<tips class="gray inblk scale8">自定义footerViewHtm</tips>';
    }
}

class AdminFormsController extends BaseAdminFormsMiddle
{

    public static $tmpPath = 'admin-forms';
    public static $trash   = true;//是否允许删除数据
    public static $addurl  = true;//是否显示创建数据按钮
    public static $addRoute = 'Form_levfm_forms';//自定义创建数据表单地址 - 默认使用源表单

    public static $srhtitle    = '表单名称';//模糊搜索字段名称
    public static $srhkeyWhere = " name LIKE '%{srhkey}%' ";//模糊搜索sql语句 例：name LIKE '%{srhkey}%'

    public static $limit = 20;//每页显示多少条
    public static $order = ['id DESC'];//排序

    /**
     * 列表显示字段设置
     * 例：array(
    'id'           => array('order' => null, 'name' => 'Id', 'thattr' => 'wd30 nowrap', 'merge' => []),

    'name'         => array('order' => null, 'name' => '模块名称', 'thattr' => 'wd30 nowrap', 'merge' => ['addtime']),

    'displayorder' => array('order' => null, 'name' => '排序', 'thattr' => 'wd30 nowrap', 'merge' => []),

    'uptime'       => array('order' => null, 'name' => '更新时间', 'thattr' => 'wd30 nowrap', 'merge' => []),

    );
     *
     * order: 点击字段排序
     * name: 字段名称
     * thattr: 表格th属性，放class属性内，内容举例：wd30 nowrap" style="font-size:12px
     * merge: 合并显示，多个字段合并显示到一个上
     *
     * @see BaseAdminForms::showColumns();
     */
    public static function showColumns() {
        //return parent::showColumns(); // TODO: Change the autogenerated stub
        return array(
                'id'           => array('order' => null, 'name' => 'Id', 'thattr' => 'wd30 nowrap', 'merge' => []),

                'tablename'    => array('order' => null, 'name' => '数据表名', 'thattr' => 'wd80 nowrap', 'merge' => []),

                'name'         => array('order' => null, 'name' => '表单名称', 'thattr' => ' nowrap', 'merge' => []),

                '#fieldManage' => array('order' => null, 'name' => '字段管理/简短描述', 'thattr' => 'nowrap', 'merge' => ['descs']),

                //'descs'        => array('order' => null, 'name' => '简短描述', 'thattr' => '', 'merge' => []),

                //'rules'        => array('order' => null, 'name' => '表单权限', 'thattr' => 'wd30 nowrap', 'merge' => []),

                //'settings'     => array('order' => null, 'name' => '通用设置', 'thattr' => 'wd30 nowrap', 'merge' => []),

                'totalnum'     => array('order' => null, 'name' => '数据总量', 'thattr' => 'wd30 nowrap', 'merge' => ['#uptotal']),

                'displayorder' => array('order' => 1, 'name' => '排序', 'thattr' => 'wd30 nowrap', 'merge' => []),

                'status'       => array('order' => null, 'name' => '状态', 'thattr' => 'wd30 nowrap', 'merge' => []),

                'uptime'       => array('order' => null, 'name' => '更新时间', 'thattr' => 'wd30 nowrap', 'merge' => []),

                //'addtime'      => array('order' => null, 'name' => '添加时间', 'thattr' => 'wd30 nowrap', 'merge' => []),

            );
    }

    /**
     *
     return [
        'showtype' => [
            //从上往下先到先得
            'input_{columnKey}'  => ['width'=>120,'textarea'=>1],//显示为无刷新更改字段
            'srhkey_{columnKey}' => ['or'=>['{columnKey}']],//显示为点击可搜索字段
            'status_{columnKey}' => 1,//显示为开关状态字段 status 自动
            'order_{columnKey}'  => 1,//显示为可排序输入框 含order关键字 自动
            'time_{columnKey}'   => 1,//显示为时间格式字段 含time关键字 自动
        ],
    ];
     *
     * @return array
     */
    public static function setColumnShowtype()
    {
        //return parent::setColumnShowtype(); // TODO: Change the autogenerated stub
        return [
            'showtype' => [
                //从上往下先到先得
                'input_{columnKey}'  => ['width'=>120,'textarea'=>1],//显示为无刷新更改字段
                'input_totalnum'  => ['width'=>100],//显示为无刷新更改字段
                'srhkey_{columnKey}' => ['or'=>['{columnKey}']],//显示为点击可搜索字段
                'status_{columnKey}' => 1,//显示为开关状态字段 status 自动
                'order_{columnKey}'  => 1,//显示为可排序输入框 含order关键字 自动
                'time_{columnKey}'   => 1,//显示为时间格式字段 含time关键字 自动
            ],
        ];
    }

    public static function formatListsv($sv, $lists)
    {
        $v = $sv;
        $sv = parent::formatListsv($sv, $lists); // TODO: Change the autogenerated stub
        $sv['#fieldManage'] = '<div class="buttons-row scale8 wd100 wdmin transl"><a class="button-fill button color-black" href="'.UrlfmHelper::fieldManageUrl($v['id']).'">字段管理</a>';
        $sv['#fieldManage'].= '<a class="button-fill button color-green" target="_blank" _bk="1" href="'.UrlfmHelper::formPreview($v['id']).'">预览</a>';
        $sv['#fieldManage'].= '<a class="button-fill button color-orange" target="_blank" _bk="1" href="'.UrlfmHelper::lists($v['id']).'">列表</a>';
        $sv['#fieldManage'].= '<a class="button-fill button color-gray" href="'.UrlfmHelper::checkData($v['id']).'">审核</a>';
        $sv['#fieldManage'].= '<a class="button-fill button color-red openPP" title="表单权限设置" href="'.Lev::toReRoute(['Form_levfm_forms', 'setup'=>5, 'opid'=>$v['id'], 'id'=>'levfm']).'"><svg class="icon"><use xlink:href="#fa-set"></use></svg>权限</a>';
        $sv['#fieldManage'].= '<a class="button-fill button color-black openPP" title="表单分类搜索设置" href="'.Lev::toReRoute(['Form_levfm_forms', 'setup'=>3, 'opid'=>$v['id'], 'id'=>'levfm']).'"><svg class="icon"><use xlink:href="#fa-sousuo"></use></svg>分类搜索</a>';
        $sv['#fieldManage'].= '</div>';

        $sv['#uptotal'] = '<a href="'.Lev::toReRoute(['admin-forms/totalnum', 'opid'=>$v['id']]).'" class="ajaxBtn">重新统计</a>';

        $sv['tablename'] = $sv['tablename'] ?: 'levfm_datas';
        return $sv;
    }

    public static function formatUid($sv, $lists, $srhkey = ['uid'])
    {
        return parent::formatUid($sv, $lists, $srhkey); // TODO: Change the autogenerated stub
    }

    public static function redirct($columnKey, $sv)
    {
        //return parent::redirct($columnKey, $sv); // TODO: Change the autogenerated stub
        switch ($columnKey) {
            case 'name': $a = '<a _bk=1 target=_blank class="date inblk" href="'.fmUrlHelper::formPreview($sv['id'], null).'"><svg class="icon color-black"><use xlink:href="#fa-huoj"></use></svg></a>'; break;
            default: $a = ''; break;
        }
        return $a;
    }

    public static function optButtons($sv)
    {
        //return parent::optButtons($sv); // TODO: Change the autogenerated stub
        $btns[] = [
            'name' => '<svg class="icon"><use xlink:href="#fa-logout"></use></svg>导出表单',
            'link' => Lev::toReRoute(['admin-forms/export', 'formid'=>$sv['id']]),
            'attr' => 'color-orange ajaxBtn" confirmmsg="它将覆盖原有导出，您确定要导出【'.$sv['name'].'】表单吗？'
        ];
        $btns[] = [
            'name' => '<svg class="icon color-orange"><use xlink:href="#fa-login"></use></svg>导入',
            'link' => Lev::toReRoute(['admin-forms/import', 'formid'=>$sv['id'], 'imformid'=>$sv['imformid']?:$sv['id']]),
            'attr' => 'color-black ajaxBtn"'
        ];

        $htms = '<div class="wd60 nowrap flex-box">';
        foreach ($btns as $v) {
            $htms .= '<a class="button button-fill wd100 wdmin '.$v['attr'].'" href="' . $v['link'] . '">'.$v['name'].'</a>';
        }
        return $htms.'</div>&nbsp;';
    }

    public static function footerBtns($btns = [])
    {
        $btns = parent::footerBtns($btns); // TODO: Change the autogenerated stub
        $btns['import'] = [
            'name' => '<svg class="icon"><use xlink:href="#fa-login"></use></svg> 导入表单',
            'link' => Lev::toReRoute(['admin-forms/import-list']),
            'attr' => 'color-yellow openPP" title="导入表单',
        ];
        return $btns;
    }

}